<template>
    <el-dialog :title="title" :visible.sync="dialogVisible" width="1400px" append-to-body v-loading="loading">
        <div class="tool-box">
            <el-button type="primary" plain icon="el-icon-plus" :loading="save" :disabled="save" @click="submit">提交批量修改</el-button>
        </div>
        <!-- <hot-table ref="hotTable" :settings="hotSettings" licenseKey="non-commercial-and-evaluation" /> -->
        <div id="edit-shop-data-table" ref="hotTable"></div>
    </el-dialog>
</template>

<script>
import { queryOrderAchievement, editOrderAchievement } from '@/api/orderSource'

import { HotTable } from '@handsontable/vue'
import Handsontable from 'handsontable'
import 'handsontable/languages/zh-CN'
import { HyperFormula } from 'hyperformula'
export default {
    name: 'EditFormDialog',
    components: { HotTable },
    props: {
        value: {
            type: Boolean,
            default: false,
            required: true,
        },
        params: {
            type: Object,
            default: () => {},
        },
    },
    data() {
        return {
            // 遮罩层
            loading: false,
            save: false,
            hotSettings: {},
            tableData: [[]],
            hotInstance: {},
        }
    },
    computed: {
        title() {
            return `批量编辑`
        },
        dialogVisible: {
            get() {
                return this.value
            },
            set(val) {
                this.$emit('input', val)
            },
        },
    },

    async created() {
        this.loading = true
        const res = await queryOrderAchievement(this.params)
        this.tableData = res.data
        // this.tableData.push({
        //     total_price: `=SUM(E1:E${this.tableData.length})`,
        //     refund: `=SUM(F1:F${this.tableData.length})`,
        //     freight: `=SUM(G1:G${this.tableData.length})`,
        //     material: `=SUM(H1:H${this.tableData.length})`,
        // })
        this.tableData = this.tableData.concat([
            {
                total_price: 'SUM',
                refund: 'SUM',
                freight: 'SUM',
                material: 'SUM',
            },
            {
                total_price: `=SUM(E1:E${this.tableData.length})`,
                refund: `=SUM(F1:F${this.tableData.length})`,
                freight: `=SUM(G1:G${this.tableData.length})`,
                material: `=SUM(H1:H${this.tableData.length})`,
            },
        ])
        this.$nextTick(() => {
            this.initTable()
            this.loading = false
        })
    },
    methods: {
        initTable() {
            const container = document.querySelector('#edit-shop-data-table')
            const height = this.tableData.length > 20 ? window.innerHeight * 0.76 : 'auto'
            this.hotInstance = new Handsontable(container, {
                data: this.tableData,
                minCols: 10,
                minRows: 10,
                licenseKey: 'non-commercial-and-evaluation',
                className: 'htCenter htMiddle',
                // selectionMode: 'single',
                manualRowResize: true,
                manualColumnResize: true,
                colHeaders: true,
                rowHeaders: true,
                language: 'zh-CN',
                mergeCells: true,
                copyPaste: true,
                colWidths: 120,
                height: height,
                width: '100%',
                autoWrapRow: true,
                autoWrapCol: true,
                rowHeights: 30,
                columnSorting: true,
                columns: [
                    {
                        title: '日期',
                        type: 'text',
                        data: 'created_at',
                        width: 180,
                    },
                    {
                        title: '订单号',
                        type: 'text',
                        data: 'name',
                    },
                    {
                        title: '支付状态',
                        type: 'text',
                        data: 'financial_status',
                    },
                    {
                        title: '物流状态',
                        type: 'text',
                        data: 'fulfillment_status',
                    },
                    {
                        title: '现销售额$',
                        type: 'numeric',
                        data: 'total_price',
                        numericFormat: {
                            pattern: '0,0.00',
                        },
                    },
                    {
                        title: '退款',
                        type: 'numeric',
                        data: 'refund',
                        numericFormat: {
                            pattern: '0,0.00',
                        },
                    },
                    {
                        title: '物流成本RMB',
                        type: 'numeric',
                        data: 'freight',
                        numericFormat: {
                            pattern: '0,0.00',
                        },
                    },
                    {
                        title: '采购成本RMB',
                        type: 'numeric',
                        data: 'material',
                        numericFormat: {
                            pattern: '0,0.00',
                        },
                    },
                    // {
                    //     title: '美金汇率',
                    //     type: 'text',
                    //     data: '_美金汇率',
                    // },
                    // {
                    //     title: '币种',
                    //     type: 'text',
                    //     data: '_币种',
                    // },
                    {
                        title: '渠道标签',
                        type: 'text',
                        data: 'tag_source',
                    },
                    {
                        title: '运营标签',
                        type: 'text',
                        data: 'tag_campaign',
                    },
                ],
                // afterChange: function (changes, sources) {
                //     console.log(changes, sources) // changes为数组数据改变后的坐标（row,col），sources改变的类型(具体参见文档)
                //     if (sources == 'edit') {
                //         changes.forEach(([row, prop, oldValue, newValue]) => {
                //             //this 表示当前的handsontable对象
                //             let cell = this.getCell(row, prop)
                //             cell.style.background = 'lavender'
                //         })
                //     }
                // },
                // dropdownMenu: ['filter_by_condition', 'filter_by_value', 'filter_action_bar'],
                contextMenu: true, // 右键
                formulas: {
                    // 公式
                    engine: HyperFormula,
                },
                filters: true, // 下拉筛选
                dropdownMenu: ['filter_by_condition', 'filter_by_value', 'filter_action_bar'],
                fixedRowsBottom: 2,
                
                afterFilter() {
                    const filtersPlugin = this.getPlugin('filters')
                    const filtersRowsMap = filtersPlugin.filtersRowsMap

                    filtersRowsMap.setValueAtIndex(filtersRowsMap.indexedValues.length - 2, false)
                    filtersRowsMap.setValueAtIndex(filtersRowsMap.indexedValues.length - 1, false)
                },
            })
        },

        submit() {
            this.$confirm('是否确认批量修改？', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    this.save = true
                    const checkList = this.hotInstance.getSourceData()
                    editOrderAchievement(checkList)
                        .then(res => {
                            this.$message.success(res.msg)
                            this.dialogVisible = false
                            this.$emit('update')
                        })
                        .finally(() => {
                            this.save = false
                        })
                })
                .catch(() => {})
        },
        // 搜索按钮操作
        handleQuery() {
            this.pageInfo.page = 1
            this.getList()
        },

        // 重置按钮操作
        resetQuery() {
            this.resetForm('queryForm')

            this.handleQuery()
        },
    },
}
</script>

<style>
.htDropdownMenu:not(.htGhostTable),
.htContextMenu:not(.htGhostTable) {
    z-index: 9000;
}
.tool-box {
    position: fixed;
    right: 0;
    top: 40%;
    background: transparent;
    padding: 12px;
    z-index: 9001;
}
</style>
